# coding:utf-8
"""

帮助方法

生成uuid
生成mac

"""
import libvirt
import os
import random

def xml_append(old, xml):
    return str(old) + str(xml);
    

"""
cpu平台
"""
def get_default_arch():
    arch = os.uname()[4]
    if arch == "x86_64":
        return "x86_64"
    return "i686"

"""
随机mac地址
"""
def randomMAC(type="xen"):
    ouis = { 'xen': [ 0x00, 0x16, 0x3E ], 'qemu': [ 0x52, 0x54, 0x00 ] }

    try:
        oui = ouis[type]
    except KeyError:
        oui = ouis['xen']

    mac = oui + [
            random.randint(0x00, 0xff),
            random.randint(0x00, 0xff),
            random.randint(0x00, 0xff)]
    return ':'.join(map(lambda x: "%02x" % x, mac))

"""
随机 UUID
"""
def randomUUID():
    
    return [ random.randint(0, 255) for dummy in range(0, 16) ]

def uuidToString(u):
    return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2,
                     "%02x" * 6]) % tuple(u)

def uuidFromString(s):
    s = s.replace('-', '')
    return [ int(s[i : i + 2], 16) for i in range(0, 32, 2) ]


def get_host_network_devices():
    device = []
    for dirname in ['', '/sbin/', '/usr/sbin']:
        executable = os.path.join(dirname, "ifconfig")
        if not os.path.exists(executable):
            continue
        try:
            cmd = 'LC_ALL=C %s -a 2>/dev/null' % (executable)
            pipe = os.popen(cmd)
        except IOError:
            continue
        for line in pipe:
            if line.find("encap:Ethernet") > 0:
                words = line.lower().split()
                for i in range(len(words)):
                    if words[i] == "hwaddr":
                        device.append(words)
    return device

"""
获取最大Vcpus
"""
def get_max_vcpus(conn, type=None):
    if type is None:
        type = conn.getType()
    try:
        m = conn.getMaxVcpus(type.lower())
    except libvirt.libvirtError:
        m = 32
    return m

"""
最大物理cpu
"""
def get_phy_cpus(conn):
    
    hostinfo = conn.getInfo()
    pcpus = hostinfo[4] * hostinfo[5] * hostinfo[6] * hostinfo[7]
    return pcpus

"""
执行一个命令
"""
def system(cmd):
    st = os.system(cmd)
    if os.WIFEXITED(st) and os.WEXITSTATUS(st) != 0:
        raise OSError("Failed to run %s, exited with %d" % 
                      (cmd, os.WEXITSTATUS(st)));

"""
比较 mac 地址
"""
def compareMAC(p, q):
    """Compare two MAC addresses"""
    pa = p.split(":")
    qa = q.split(":")

    if len(pa) != len(qa):
        if p > q:
            return 1
        else:
            return -1

    for i in xrange(len(pa)):
        n = int(pa[i], 0x10) - int(qa[i], 0x10)
        if n > 0:
            return 1
        elif n < 0:
            return -1
    return 0


if(__name__ == "__main__"):
    
    uuid = randomUUID();
    us = uuidToString(uuid);
    ui = uuidFromString(us);
    
    print uuid;
    print us;
    print ui;
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
